<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item> <i class="el-icon-lx-cascades"></i> 题库 </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
                <el-tab-pane label="题库管理" name="first">
                    <el-button type="primary" class="add_btn" @click="addCategory">新增题库</el-button>
                    <el-table :data="classifyList" style="width: 100%; margin-bottom: 20px" row-key="id" border :tree-props="{ children: '_child' }" @expand-change="sliderChange">
                        <el-table-column label="课程名称">
                            <template slot-scope="{row}">
                                <div class="name">								
                                    <span>{{ row.title }}</span>
                                </div>
                            </template>
                        </el-table-column>
                        <!-- <el-table-column prop="status" label="状态">
                            <template slot-scope="{row}">
                                <div :class="row.status > 0 ? 'on' : 'off'">{{ row.status == 0 ? '禁用' : '启用' }}</div>
                            </template>
                        </el-table-column> -->
                        <el-table-column label="操作" width="340" fixed="right">
                            <template slot-scope="{ row }">
                                <div v-if="row._child">
                                    <el-button @click="lookSubject(row.id, row.title)" type="warning" size="mini">查看试题</el-button>
                                    <el-button @click="addChildCategory(row.id, row.title)" type="primary" size="mini">添加子题库</el-button>
                                    <el-button @click="parentCategoryEdit(row.id, row.title, row.sort)" type="success" size="mini">编辑</el-button>
                                    <el-button @click="deleteRow(row.id)" type="danger" size="mini">删除</el-button>
                                </div>
                                <div v-else>
                                    <el-button @click="lookSubject(row.id, row.title)" type="warning" size="mini">查看试题</el-button>
                                    <el-button @click="childCategoryEdit(row.id, row.title, row.title, row.sort)" type="success" size="mini">编辑</el-button>
                                    <el-button @click="deleteRow(row.id)" type="danger" size="mini">删除</el-button>
                                </div>								
                            </template>
                        </el-table-column>
                    </el-table>
                    <!-- 新增/编辑弹出框 -->
                    <el-dialog :title="dialogTitle" :visible.sync="addOrEditVisible" width="350px">
                        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                            <el-form-item label="上级题库" v-if="form.showParentName">
                                <el-input v-model="form.parentName" :disabled="form.orEdit"></el-input>
                            </el-form-item>
                            <el-form-item label="题库名称" prop="name">
                                <el-input v-model="form.name"></el-input>
                            </el-form-item>
                            <el-form-item label="排序" prop="sort">
                                <el-input v-model="form.sort"></el-input>
                            </el-form-item>
                        </el-form>
                        <span slot="footer" class="dialog-footer">
                            <el-button @click="cancel">取 消</el-button>
                            <el-button type="primary" @click="save('form')">确 定</el-button>
                        </span>
                    </el-dialog>
                </el-tab-pane>
				
                <el-tab-pane label="添加题目" name="second">
                    <div class="addSubject card">
                        <h4 class="title">新增/编辑 试题</h4>
                        <el-form class="subject_form" ref="form" :model="dynamicValidateForm" label-width="100px">
                            <el-form-item label="所属题库">
                                <el-select v-model="dynamicValidateForm.category_id" clearable placeholder="所属题库">
                                    <el-option v-for="item in options" :key="item.id" :label="item.title"
                                        :value="item.id"></el-option>
                                    <el-option-group v-for="group in options" :key="group.index">
                                        <el-option v-for="item in group._child" :key="item.id" :label="item.title"
                                            :value="item.id"></el-option>
                                    </el-option-group>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="题目类型">
                                <el-select v-model="dynamicValidateForm.type" placeholder="请选择试题类型" clearable
                                    class="handle-select mr10">
                                    <el-option key="1" label="单选题" value="1"></el-option>
                                    <el-option key="2" label="多选题" value="2"></el-option>
                                    <el-option key="3" label="判断题" value="3"></el-option>
									<el-option key="4" label="填空题" value="4"></el-option>
									<el-option key="5" label="问答题" value="5"></el-option>
									<el-option key="6" label="材料题" value="6"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="题目问题">
                                <el-input id="topic" type="textarea" :rows="4" v-model="dynamicValidateForm.question"></el-input>
                            </el-form-item>
                            <el-form-item label="题目配图">
                               <div class="avatar-uploader" @click="showUploadImage()">
						         <img v-if="dynamicValidateForm.question_img" :src="dynamicValidateForm.question_img" class="avatar" height="200px">
						         <i v-else class="el-icon-plus avatar-uploader-icon"></i>
					           </div>
                               <div class="el-upload__tip">封面建议尺寸：800*600px，支持jpg、png</div>
                            </el-form-item>
							
                            <div class="domains_fileds"
                                v-if="this.dynamicValidateForm.type == 1 || this.dynamicValidateForm.type == 2">
                                <div class="domain_title">
                                    <span>选择题选项</span>
                                </div>
                                <el-form-item v-for="(domain, index) in domains" :label="domain.option"
                                    :key="domain.option">
                                    <el-input v-model="domain.description" placeholder="请输入选项内容" style="width: 600px">
                                    </el-input>
                                    <el-button @click.prevent="removeDomain(domain, index)" type="text"
                                        style="margin-left: 20px">删除</el-button>
                                </el-form-item>
                            </div>
							
							<div class="domains_fileds" v-if="this.dynamicValidateForm.type == 4">
							    <div class="domain_title">
							        <span>填空题选项</span>
							    </div>
							    <el-form-item>
							        <!-- <el-input v-model="domain.description" placeholder="请输入选项内容" style="width: 300px"></el-input> -->
							        <!-- <el-button @click.prevent="removeDomain(domain, index)" type="text" style="margin-left: 20px">删除</el-button> -->
									<el-button @click="addFillin" type="primary" size="small">+增加填空</el-button>
							    </el-form-item>
							</div>
							
                            <el-form-item
                                v-if="this.dynamicValidateForm.type == 1 || this.dynamicValidateForm.type == 2">
                                <el-button @click="addDomain" type="primary" size="small">+增加选项</el-button>
                            </el-form-item>

                            <!-- <el-form-item label="正确答案">
                                <el-select v-model="answer_right" multiple placeholder="请选择正确答案"
                                    v-if="this.dynamicValidateForm.type == 1 || this.dynamicValidateForm.type == 2">
                                    <el-option v-for="item in domains" :key="item.option" :label="item.option"
                                        :value="item.option">
                                    </el-option>
                                </el-select>
                                <el-radio-group v-model="answer_right" v-if="this.dynamicValidateForm.type == 3">
                                    <el-radio :label="1">正确</el-radio>
                                    <el-radio :label="0">错误</el-radio>
                                </el-radio-group>
                            </el-form-item> -->
							
							<el-form-item label="正确答案">
							    <el-select
							        v-model="answer_right"
							        multiple
							        placeholder="请选择正确答案"
							        v-if="this.dynamicValidateForm.type == 1 || this.dynamicValidateForm.type == 2"
							    >
							        <el-option v-for="item in domains" :key="item.option" :label="item.option" :value="item.option"> </el-option>
							    </el-select>
								
							    <el-radio-group v-model="dynamicValidateForm.answer" v-if="this.dynamicValidateForm.type == 3">
							        <el-radio :label="1">正确</el-radio>
							        <el-radio :label="0">错误</el-radio>
							    </el-radio-group>
								
								<!-- 填空题 -->
								<div class="domains_fileds" v-if="this.dynamicValidateForm.type == 4 && this.fillins.length > 0">
								    <el-form-item v-for="(fillin, index) in fillins" :label="fillin.option" :key="fillin.option">
								        <el-input v-model="fillin.description" placeholder="请输入填空答案" style="width: 300px"></el-input>
								        <el-button @click.prevent="removeFillin(fillin, index)" type="text" style="margin-left: 20px">删除</el-button>
								    </el-form-item>
								</div>
								
							</el-form-item>

                            <el-form-item label="讲解">
                                <el-input type="textarea" placeholder="讲解" :rows="4" v-model="dynamicValidateForm.exp">
                                </el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="primary" @click="onSubmit">确认提交</el-button>
                            </el-form-item>
                        </el-form>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
         <uploadimage ref="uploadimagecom" v-on:childByImageValue="childByImageValue"></uploadimage>
    </div>
</template>

<script>
import {
    questionCategoryListData,
    addQuestionCategoryData,
    editQuestionCategoryData,
    delQuestionCategoryData,
    addQuestionData
} from '../../api/index';
import uploadimage from '@/components/common/uploadimage.vue';
export default {
    components: {
		uploadimage
	},
    data() {
        return {
            activeName: 'first',
            classifyList: [],
            addOrEditVisible: false,
            dialogTitle: '',
            form: {
                id: '',
                name: '',
                sort: '',
                showParentName: false,
                parentName: '',
                orEdit: true
            },
            rules: {
                name: [{ required: true, message: "请输入题库名称", trigger: "blur" }],
                sort: [{ required: true, message: "请输入排序", trigger: "blur" }]
            },
            imgUrl: '',
            alpha: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N'],
            removeList: [],
            // 添加题目form
            domains: [
                {
                    option: 'A',
                    description: ''
                }
            ],
			delta: ['1', '2', '3', '4', '5', '6', '7', '8', '9'],
			fillins: [
			    // {
			    //     option: '1',
			    //     description: ''
			    // }
			],
            answer_right: [],
            dynamicValidateForm: {
                category_id: '',
                type: '1',
                question: '',
                question_img: '',
                options: [],
                answer: '',
                exp: ''
            },
            options: [],
			questionType: [
			    {
			        value: 1,
			        label: '单选题'
			    },
			    {
			        value: 2,
			        label: '多选题'
			    },
			    {
			        value: 3,
			        label: '判断题'
			    },
			    {
			        value: 4,
			        label: '填空题'
			    },
			    {
			        value: 5,
			        label: '问答题'
			    },
			    {
			        value: 6,
			        label: '材料题'
			    },
			],
            dialogVisible:false,
            errorProduct: require('@/assets/img/noProduct.jpg'), 
        };
    },
    created() {
        this.getData();
    },
    methods: {
        tabErrorPicture(id,data){    // 表格图文封面默认展示图
            let i = this[data].findIndex(v => v.id == id);
			this[data][i].cover = this.errorProduct;
        },
		tabErrorChildPicture(v){    // 表格图文封面子级默认展示图
			v.cover = this.errorProduct;
		},
		sliderChange(row,bool){	// 表格展开、收起
			let i = this.classifyList.findIndex(v => v.id == row.id);
			bool && this.classifyList[i]._child.forEach(v => this.tabErrorChildPicture(v));
		},
        getData() {
            questionCategoryListData().then((res) => {
                this.classifyList = res.data.list;
                this.options = res.data.list;
            });
        },
        handleClick(tab, event) {
            // console.log(tab, event);
        },
        addCategory() {
            this.form = {};
            this.form.id=0;
            this.addOrEditVisible = true;
            this.dialogTitle = '新增';
        },
        lookSubject(id, title) {
            this.$router.push({ path: '/aidTool/questionbank_detail', query: { id, title } });
        },
        addChildCategory(id, title) {
            this.form = {};
            this.addOrEditVisible = true;
            this.form.showParentName = true;
            this.form.id = id;
            this.form.parentName = title;
            this.form.orEdit = true;
            this.dialogTitle = '新增';
        },
        parentCategoryEdit(id, title, sort) {
            this.addOrEditVisible = true;
            this.form.showParentName = false;
            this.form.id = id;
            this.form.name = title;
            this.form.sort = sort;
            this.dialogTitle = '编辑';
        },
        childCategoryEdit(id, Ptitle, Stitle, sort) {
            this.addOrEditVisible = true;
            this.form.showParentName = true;
            this.form.id = id;
            this.form.parentName = Ptitle;
            this.form.name = Stitle;
            this.form.sort = sort;
            this.dialogTitle = '编辑';
        },
        //删除
        deleteRow(id) {
            // 二次确认删除
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            }).then(() => {
                delQuestionCategoryData({ id: id }).then((res) => {
                    if (res.code == 1) {
                        this.$message.success('删除成功');
                        this.getData();
                    }
                });
            });
        },
        cancel() {
            this.addOrEditVisible = false;
        },
        save(formName) {
            if (this.dialogTitle == '新增') {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        addQuestionCategoryData({ pid: this.form.id, title: this.form.name, sort: this.form.sort }).then((res) => {
                            if (res.code == 1) {
                                this.addOrEditVisible = false;
                                this.$message.success('新增题库成功');
                                this.getData();
                            }
                        });
                    } else {
                        return false
                    }
                })
            } else {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        editQuestionCategoryData({ id: this.form.id, title: this.form.name, sort: this.form.sort }).then((res) => {
                            if (res.code == 1) {
                                this.addOrEditVisible = false;
                                 this.$message.success('题库修改成功');
                                this.getData();
                                //location.reload();
                            }
                        });
                    } else {
                        return false
                    }
                })
            }
        },
        // 封面上传
        handleCover(res) {
            if (res.code == 1) {
                this.dynamicValidateForm.question_img = res.data.attachment;
            }
        },

        handleRemove(file, fileList) {
            // console.log(file, fileList);
        },

        getArrDifference(arr1, arr2) {
            return arr1.concat(arr2).filter(function (v, i, arr) {
                return arr.indexOf(v) === arr.lastIndexOf(v);
            });
        },

        array_intersection(a, b) {
            // 交集
            var result = [];
            for (var i = 0; i < b.length; i++) {
                var temp = b[i];
                for (var j = 0; j < a.length; j++) {
                    if (temp === a[j]) {
                        result.push(temp);
                        break;
                    }
                }
            }
            return result;
        },
		addFillin() {//添加 填空
			// 在题目文本域 里面 append 一个 __  并且在 正确答案 添加一个文本框 元素
			
			var content = this.dynamicValidateForm.question;
			content = content + ' __ ';
			this.dynamicValidateForm.question = content;
			
		    let fillinObj = []; //添加的答题选项的abc值保存
		    let fillinLen = this.fillins.length; //答题选项长度获取
		    let deltaObj = this.delta.slice(0, fillinLen); //截取alpha字符串长度作为数组
		    this.fillins.map((res) => {
		        fillinObj.push(res.option);
		    });
		    let unqualList = this.getArrDifference(deltaObj, fillinObj); //获取字符串中不相等的内容
		    if (unqualList.length > 0) {
		        let interList = this.array_intersection(unqualList, deltaObj); //交集的数组
		        let deltaIndex = deltaObj.indexOf(interList[0]);
		        this.fillins.splice(deltaIndex, 0, {
		            option: this.delta[deltaIndex],
		            description: ''
		        });
		    } else {
		        this.fillins.push({
		            option: this.delta[this.fillins.length],
		            description: ''
		        });
		    }
		},
		
		//删除 填空
		removeFillin(item, index) {
		    this.removeList.push(index);
		    var index = this.fillins.indexOf(item);
		    if (index !== -1) {
		        this.fillins.splice(index, 1);
				
				var content = this.dynamicValidateForm.question;
				var con_len = content.length;
				var lastIndex = 0;
				
				this.dynamicValidateForm.question = content.slice(0,content.lastIndexOf(' __ '));
		    }
		    if (this.answer_right.length > 0) {
		        this.answer_right.forEach((res, index) => {
		            if (res == item.option) {
		                this.answer_right.splice(index, 1);
		            }
		        });
		    }
		},
		
        addDomain() {
            let domainObj = []; //添加的答题选项的abc值保存
            let domainLen = this.domains.length; //答题选项长度获取
            let alphaObj = this.alpha.slice(0, domainLen); //截取alpha字符串长度作为数组
            this.domains.map((res) => {
                domainObj.push(res.option);
            });
            let unqualList = this.getArrDifference(alphaObj, domainObj); //获取字符串中不相等的内容
            if (unqualList.length > 0) {
                let interList = this.array_intersection(unqualList, alphaObj); //交集的数组
                let alphaIndex = alphaObj.indexOf(interList[0]);
                this.domains.splice(alphaIndex, 0, {
                    option: this.alpha[alphaIndex],
                    description: ''
                });
            } else {
                this.domains.push({
                    option: this.alpha[this.domains.length],
                    description: ''
                });
            }
        },
		
        //删除选项
        removeDomain(item, index) {
            this.removeList.push(index);
            var index = this.domains.indexOf(item);
            if (index !== -1) {
                this.domains.splice(index, 1);
            }
            if (this.answer_right.length > 0) {
                this.answer_right.forEach((res, index) => {
                    if (res == item.option) {
                        this.answer_right.splice(index, 1);
                    }
                });
            }
        },
        onSubmit() {
            let str = '';
            this.dynamicValidateForm.options = this.domains;
            if(this.dynamicValidateForm.type==1||this.dynamicValidateForm.type==2){
            if (this.answer_right.length > 0) {
                this.answer_right.forEach((item) => {
                    str += item + ',';
                });
                this.dynamicValidateForm.answer = str.slice(0, str.length - 1);
                // console.log(this.dynamicValidateForm.options)
                // console.log(this.dynamicValidateForm.answer)
            }}else if(this.dynamicValidateForm.type==3){
                this.dynamicValidateForm.answer=this.answer_right;
            }
            addQuestionData(this.dynamicValidateForm).then((res) => {
                if (res.code == 1) {
                    this.$message.success('添加题目成功');
                    this.getData();
                }
            });
        },
        showUploadImage() { //显示上传组件
			this.$refs.uploadimagecom.dialogVisible = true;
		},
        //确认按钮传值过来并赋值到form表单上
		childByImageValue: function (childValue) {
			this.dynamicValidateForm.question_img = childValue;
		}
    }
};
</script>

<style scoped>
@import '~@/components/common/css/common.css';
::v-deep .container .el-table .cell{
    display: flex;
}
.container .add_btn{
    margin: 0 0 10px 0;
}

.category-list-section {
    margin-top: 20px;
}

.category-list-section .category {
    padding: 10px;
}

.card {
    box-shadow: 0 0 20px rgb(0 0 0 / 8%);
    background-color: #fff;
    border-radius: 5px;
    border: none;
    margin-bottom: 30px;
}

.category-list-section .child-item,
.category-list-section .parent-item {
    border-left: 1px #ccc dashed;
    border-right: 1px #ccc dashed;
    border-bottom: 1px #ccc dashed;
    padding: 26px 30px;
}

.category-list-section .parent-item {
    border-top: 1px #ccc dashed;
    margin: 10px 10px 0;
}

.tac {
    margin: -16px;
}

.category-list-section .title {
    float: left;
    width: 400px;
    line-height: 32px;
}

.category-list-section .child-item .title {
    width: 358px;
}

.category-list-section .title .info {
    margin-left: 42px;
}

.category-list-section .action {
    float: right;
    line-height: 32px;
}

.category-list-section .child-item {
    margin: 0 10px 0 52px;
}

.addSubject .title {
    padding: 20px;
    color: #000;
    background-color: #f6f6f6;
}

.subject_radio {
    margin-top: 20px;
}

.subject_form {
    padding: 50px 40px;
}

.m20 {
    margin-right: 20px;
}

/*  */
.domain_title {
    margin: 10px;
    justify-content: space-between;
    display: flex;
}

.el-tabs__content {
    margin-top: 10px;
}
.avatar-uploader {
	border: 1px dashed #d9d9d9;
	border-radius: 6px;
	cursor: pointer;
	position: relative;
	overflow: hidden;
	width: 375px !important;
	text-align: center;
}

.avatar-uploader:hover {
	border-color: #409EFF;
}

.avatar-uploader-icon {
	font-size: 28px;
	color: #8c939d;
	width: 178px;
	height: 178px;
	line-height: 178px;
}

.avatar {
	width: 100%;
	display: block;
}
</style>